﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Models.ClassifyColumn;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    public class ClassifyColumnController : Controller
    {
        private IClassifyColumnService _icfSvc;
        private IUsersService _usersSvc;
        public ClassifyColumnController(IClassifyColumnService icfSvc, IUsersService usersSvc)
        {
            _icfSvc = icfSvc;
            _usersSvc = usersSvc;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _icfSvc.GetByNameAsync(search);
            var ColumnList = new List<ClassifyColumnLsitViewModel>();
            foreach (var item in data) 
            {
                var model = new ClassifyColumnLsitViewModel
                {
                    Id = item.Id,
                    Title = item.Title,
                    UsersTitle = await GetUsersTitle(item.Uid),
                    CreateTime = item.CreateTime,
                    UpdateTime = item.UpdateTime
                };
                ColumnList.Add(model);
            }

            ViewBag.Search = search;
            var pages = await ColumnList.ToPagedListAsync(page,PageConfig.PageSize);
            return View(pages);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _icfSvc.GetByIdAsync(id);
            return View(new ClassifyColumnUpdateViewModel 
            {
                Id= data.Id,
                Title= data.Title,
                UsersId = data.Uid
            });
        }

        [HttpPost]
        public async Task<IActionResult> Update(ClassifyColumnUpdateViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _icfSvc.UpdateClassifyColumnAsync(model.Id,model.Title,model.UsersId);
                return Redirect("~/ForumManage/ClassifyColumn/Index");
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _icfSvc.PutTrashAsync(id);
            return Redirect("~/ForumManage/ClassifyColumn/Index");
        }

        private async Task<string> GetUsersTitle(int id) 
        {
            var data = await _usersSvc.GetByIdAsync(id);
            return data == null ? "" : data.NickName;
        }

    }
}
